package cn.wolfcode.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRolePermissionService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author jishushen
 * @create 2021-02-19 14:44
 * 系统管理之权限管理
 */
@Api(value = "权限列表",description = "权限源控制器")
@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    @Autowired
    private ApplicationContext ctx;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"permission:list","权限列表"},logical = Logical.OR)
    public String list(QueryObject qo, Model model){
        PageInfo<Permission> pageInfo = permissionService.listpage(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "permission/list";
    }

    @GetMapping("/delete")
    public String delete(Long id){
        //先删除权限
        permissionService.deleteByPrimaryKey(id);
        //再根据权限Id删除role_permission里的
        rolePermissionService.deleteByPermissionId(id);
        return "redirect:/permission/list.do";
    }

    @GetMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        try {
            //1、获取数据库中全部的权限表达式
            List<String> list = permissionService.selectPermissionExpression();
            //2、找IOC要所有含有@controller注解的bean
            Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
            //3、获取values,放到一个集合中
            Collection<Object> collectionCglibProxys = beans.values();
            for (Object  controllerCglisbProxy: collectionCglibProxys) {
                //判断controllerCglisbProxy是否为Cglib动态代理
                if (!AopUtils.isCglibProxy(controllerCglisbProxy)){
                    //不是cglib的动态代理，继续循环
                    continue;
                }
                //是cglib的动态代理,获取真实controller类
                Class controller = controllerCglisbProxy.getClass().getSuperclass();
                //使用反射的方式，获取controller类中的所有方法
                Method[] methods = controller.getDeclaredMethods();
                //遍历方法，看方法上面是否有RequiresPermissions注解
                for (Method method : methods) {
                    RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                    if (annotation != null){
                        //注解不为空，获取注解上面的value值
                        String[] value = annotation.value();
                        String expression = value[0];
                        String name = value[1];
                        //如果list查询数据库中所有的权限，不包含注解中的expression那么就添加到数据库
                        if (!list.contains(expression)){
                            Permission permission = new Permission();
                            permission.setName(name);
                            permission.setExpression(expression);
                            permissionService.insert(permission);
                        }
                    }
                }

            }
            return new JsonResult(true,"操作成功");
        } catch (Exception e) {
            return new JsonResult(false,"重新加载失败");
        }
    }
}
